package com.shxzz.easy12306.framework.starter.convention.result;

import com.shxzz.easy12306.framework.starter.convention.errorcode.BaseErrorCode;
import com.shxzz.easy12306.framework.starter.convention.exceptions.AbstractException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Optional;

/**
 * 创建统一响应实体工具类
 * @author shxzz
 * @create 2024-01-25-23:26
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Results {

    /**
     * 构建成功响应
     */
    public static Result<Void> success() {
        return new Result<Void>()
                .setCode(Result.SUCCESS_CODE);
    }

    /**
     * 构建带返回数据的成功响应
     */
    public static <T> Result<T> success(T data) {
        return new Result<T>()
                .setCode(Result.SUCCESS_CODE)
                .setData(data);
    }

    /**
     * 构建默认失败响应
     */
    public static Result<Void> failure() {
        return new Result<Void>()
                .setCode(BaseErrorCode.SERVICE_ERROR.code())
                .setMessage(BaseErrorCode.SERVICE_ERROR.message());
    }

    /**
     * 构建失败响应
     */
    public static Result<Void> failure(String code, String message) {
        return new Result<Void>()
                .setCode(code)
                .setMessage(message);
    }

    /**
     * 根据异常 {@link AbstractException} 构建失败响应
     */
    public static Result<Void> failure(AbstractException exception) {
        String errorCode = Optional.ofNullable(exception.getErrorCode()).orElse(BaseErrorCode.SERVICE_ERROR.code());
        String errorMsg = Optional.ofNullable(exception.getErrorMsg()).orElse(BaseErrorCode.SERVICE_ERROR.message());

        return new Result<Void>()
                .setCode(errorCode)
                .setMessage(errorMsg);
    }
}
